package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.UserCacheConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserAuth;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class LoginServiceImpI implements LoginService {

    /**
     * @author     ：zhangheng
     * @date       ：Created in 2024/9/8 11:15
     * @description：登录接口
     * @modified By：
     * @version: 1.0
     */
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private SecurityConfigProperties securityConfigProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public UserVo login(LoginDto loginDto) {
    //使用认证管理器来识别用户进行认证
        UsernamePasswordAuthenticationToken upat=new UsernamePasswordAuthenticationToken(loginDto.getUsername(),loginDto.getPassword());
        Authentication authenticate=authenticationManager.authenticate(upat);
        if (!authenticate.isAuthenticated()){
          throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //获取用户数据
        UserAuth userAuth= (UserAuth) authenticate.getPrincipal();
        UserVo userVo= BeanUtil.toBean(userAuth,UserVo.class);
        //敏感数据处理
        userVo.setPassword("");
        //获取用户资源列表
        List<Resource> resourceList= resourceMapper.findResourceVoListByUserId(userVo.getId());
        List<String> resourcePath = resourceList.stream().map(Resource::getRequestPath).collect(Collectors.toList());
        //获取白名单列表
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        //合并列表
        resourcePath.addAll(publicAccessUrls);
        //生成jwt令牌
        Map<String,Object>clamis=new HashMap<>();
        clamis.put("currentUser", JSONUtil.toJsonStr(userVo));
        String jwtToken = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), clamis);
        //封装token返回用户信息
        userVo.setUserToken(jwtToken);
        //存储数据到redis中
        Long ttl = Long.valueOf(jwtTokenManagerProperties.getTtl()/1000);
        String accessUrlsCachekey=UserCacheConstant.ACCESS_URLS_CACHE+userVo.getId();
        stringRedisTemplate.opsForValue().set(accessUrlsCachekey,JSONUtil.toJsonStr(resourcePath),ttl, TimeUnit.SECONDS);
        return userVo;
    }

}

